import numpy as np
import cv2

import matplotlib.pyplot as plt

# 定义多边形的顶点坐标
polygon_vertices = np.array([(1, 1), (4, 2), (3, 4), (2, 4)]) *100


# 定义点集
pc = np.array([(2, 2), (3, 3), (3, 2), (4, 3), (1, 3)])*100

# 绘制多边形
polygon = plt.Polygon(polygon_vertices, closed=True, fill=None, edgecolor='black')
plt.gca().add_patch(polygon)

# 判断点是否在多边形内部的函数
def point_inside_polygon(point, vertices):
    x, y = point
    print("x y ",x,y)
    inside = False
    j = len(vertices) - 1
    # 0,-1(3)
    # 1,0
    # 2,1
    # 3,2
    for i in range(len(vertices)):
        xi, yi = vertices[i]
        xj, yj = vertices[j] # 最后一个顶点
        '''
        (x-xi) / (xj-xi) > (y-yi)/(yj-yi)
        '''
        print("vertices pts k", xi, yi)
        print("vertices pts j", xj, yj)
        is_mid_y = (yi < y <= yj or yj < y <= yi)
        if is_mid_y:
            print("is_mid_y pts ",x, y)
            is_mid_x = (x > (xj - xi) * (y - yi) / (yj - yi) + xi)
            if is_mid_x:
                print("is_mid_x ",(xj - xi) * (y - yi) / (yj - yi) + xi)
                inside = not inside
        j = i
    print("inside",inside)
    return inside

# 初始化存储内外点的列表
points_inside = []
points_outside = []

# 遍历点集，判断每个点是否在多边形内部
for i,point in enumerate(pc):
    print(i)
    if point_inside_polygon(point, polygon_vertices):
        points_inside.append(point)
    else:
        points_outside.append(point)

# 绘制点集
if points_inside:
    x_in, y_in = zip(*points_inside)
    plt.scatter(x_in, y_in, color='blue', label='Inside Points')

if points_outside:
    x_out, y_out = zip(*points_outside)
    plt.scatter(x_out, y_out, color='red', label='Outside Points')

plt.xlabel('X')
plt.ylabel('Y')
plt.title('Points Inside and Outside Polygon')
plt.legend()
plt.grid(True)
plt.savefig("a.jpg")
# plt.show()

# 输出结果
print("Points inside polygon:", points_inside)
print("Points outside polygon:", points_outside)
